package com.corpgovernment.organization.producer;

import com.corpgovernment.api.messageadvice.enums.MsgBizType;
import com.corpgovernment.common.base.CommonException;
import com.ctrip.corp.obt.api.message.center.enums.EventBizTypeEnum;
import com.ctrip.corp.obt.api.message.center.event.MessageEvent;
import com.ctrip.corp.obt.generic.event.core.EventCenter;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;


@Component
@Slf4j
public class MessageEventProducer {

    /**
     * 大陆国际区号
     */
    private static final String CHINA_MAINLAND_AREA_CODE = "86";
    /**
     * 大陆手机号长度
     */
    private static final int CHINA_MAINLAND_PHONE_LENGTH = 11;

    @Autowired
    private EventCenter eventCenter;

    protected void publishEvent(MessageEvent messageEvent) {
        log.info("触发消息事件推送 messageEvent:{}", JsonUtils.toJsonString(messageEvent));
        eventCenter.post(messageEvent);
    }

    public void sendMessageEvent(MsgBizType bizType, String countryCode, String phone, Map<String, Object> vars) {
        CommonException commonException = new CommonException(100000, "参数不合法");
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(countryCode)) {
            log.error("手机号{}或者国际区码{}不是为空", phone, countryCode);
            throw commonException;
        }
        // 手机号和国际区码数字正则校验
        if (Objects.equals("+", countryCode.substring(0, 1))) {
            countryCode = countryCode.substring(1);
        }
        if (!Pattern.matches("\\d+", phone)) {
            log.error("手机号{}或者国际区码{}不是数字", phone, countryCode);
            throw commonException;
        }

        // 根据国际区码确认发送短信的手机号
        if (StringUtils.equals(CHINA_MAINLAND_AREA_CODE, countryCode, false)) {
            if (phone.length() != CHINA_MAINLAND_PHONE_LENGTH) {
                log.error("手机号不合法{},{}", phone, countryCode);
                throw commonException;
            }
        }

        MessageEvent messageEvent = new MessageEvent(EventBizTypeEnum.ORGANIZATION_EVENT);
        MessageEvent.Sms sms = new MessageEvent.Sms();
        sms.setBizType(bizType);
        sms.setPhone(phone);
        //sms.setCorpId();
        sms.setVars(vars);
        sms.setCountryCode(countryCode);
        //sms.setBizId();

        messageEvent.setSms(sms);
        this.publishEvent(messageEvent);
    }
}
